package com.zzyl.common.utils;

import com.zzyl.common.core.domain.AjaxResult;

import java.time.LocalDate;
import java.time.Period;

public class AgeCalculator {

    /**
     * 通过身份证号码计算年龄
     *
     * @param idCard 身份证号码
     * @return 年龄
     */
    public static int calculateAgeFromIdCard(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            throw new IllegalArgumentException("无效的身份证号码");
        }

        // 提取出生日期部分
        String birthDateString = idCard.substring(6, 14);
        int year = Integer.parseInt(birthDateString.substring(0, 4));
        int month = Integer.parseInt(birthDateString.substring(4, 6));
        int day = Integer.parseInt(birthDateString.substring(6, 8));

        // 创建出生日期
        LocalDate birthDate = null;
        try {
            birthDate = LocalDate.of(year, month, day);
        } catch (Exception e) {
            AjaxResult.error("非法的身份证~~");
        }

        // 获取当前日期
        LocalDate today = LocalDate.now();

        // 计算年龄
        return Period.between(birthDate, today).getYears();
    }
}